package uk.co.cocking.getinline2.restlet;

import org.restlet.Restlet;
import org.restlet.data.Request;
import org.restlet.data.Response;

public class ShutdownRestlet extends Restlet {
	private final RestfulServer server;

	public ShutdownRestlet(RestfulServer server) {
		this.server = server;
	}

	@Override
	public void handle(Request request, Response response) {
		System.out.println("stop request received");
		try {
			new Thread(new DelayingStopper(server)).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	class DelayingStopper implements Runnable {


		private final RestfulServer server;

		public DelayingStopper(RestfulServer server) {
			this.server = server;
		}

		@Override
		public void run() {
			System.out.println("stopping server");
			try {
				System.out.println("wait starting");
				Thread.sleep(100);
				System.out.println("wait over");
				server.stop();
				System.out.println("server stopped");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}